import {loadStatus, dataStatus} from '../utils/const'
 
module.exports = Behavior({
  properties: {
  },
  data: {
    loadStatus: {...loadStatus},
    dataStatus: {...dataStatus},
    curLoadStatus: loadStatus.none,
    curDataStatus: dataStatus.none,
    pageList: [],
    page: 1,
    totalPages: 0,
    pageSize: 10,
    nums: 0
  },
  methods: {
    requestPageData(page){
      if (!this.listPromise) {
        return
      }
      page = page ? page : this.data.page + 1
      this.listPromise({page, pageSize: this.data.pageSize}).then(res => {
        let data = res.result

        if (res.success) {
          let setData = {
            curLoadStatus: loadStatus.none,
            curDataStatus: dataStatus.none,
            page: data.page,
            totalPages: data.totalPages,
            nums: data.nums
          }
          let pageList = data.pageList || [];
          if (this.formatListData) {
            pageList = this.formatListData(pageList)
          }

          if (data.nums > this.data.pageSize && data.page === data.totalPages) {
            setData.curDataStatus = dataStatus.end
          }
          if (data.page === 1) {
            setData.curDataStatus = pageList.length > 0 ? setData.curDataStatus : dataStatus.noData 
            setData.pageList = [pageList]
            wx.stopPullDownRefresh()
          } else {
            setData[`pageList[${data.page - 1}]`] = pageList
          }
          this.setData(setData)
        } else {
          this.setData({
            curLoadStatus: loadStatus.none
          })
        }
      }).catch((err) => {
        this.setData({
          curLoadStatus: loadStatus.none
        })
      })
    },
    onLoad() {
      this.onReachBottom()
    },
    onPullDownRefresh() {
      this.setData({
        curLoadStatus: loadStatus.refresh,
      }, () => {
        this.requestPageData(1)
      })
    },
    onReachBottom() {
      if (this.curDataStatus == dataStatus.end) {
        return
      }

      this.setData({
        curLoadStatus: loadStatus.loading,
      }, () => {
        this.requestPageData()
      })
    }
  }
})